$('.message-history').livequery(function() {
	$(".mess-history table tr").click( function(event) {
		clickedElement=event.target||event.srcElement; 
		if (clickedElement.tagName != 'A') {
			url = W_ABSPATH + 'messages?user=' + $(this).attr('person');
			location.href = url;
		}
	});
});

$('.message-chat').livequery(function(){
	$('.mess-item.new-mess').live('click', function() {
		var self = $(this);
		self.removeClass('new-mess');
		$.ajax({
			dataType: 'json',
			url: W_AJAX + 'message/make-read',
			type: 'POST',
			data: {
				ID_message: self.attr('mess-num')
			},
			success: function(data) {
				if(data.result != 'OK') self.addClass('new-mess');
			}	
		});
	});
	
	$('.mess-actions .del-mess').live('click',function() {
		var messBlock = $(this).closest('.mess-item');
		if(messBlock.hasClass('deleting')) return false;
		messBlock.addClass('deleting');
		$.ajax({
			dataType: 'json',
			url: W_AJAX + 'message/del',
			type: 'POST',
			data: {
				ID_message: messBlock.attr('mess-num')
			},
			success: function(data) {console.log(data);
				if(data.result == 'OK') messBlock.slideUp(300);
				else messBlock.removeClass('deleting');
			}	
		});
		return false;
	});
	
	 canSend = true;
	$('#new-message').submit(function() {
		if(!canSend) return false;
		canSend = false;
		var self = $(this);
		$.ajax({
			dataType: 'json',
			url: W_AJAX + 'message/new',
			type: 'POST',
			data: {
				text:  $('textarea', self).val(),
				to: $('#to', self).val()
			},
			success: function(data) { console.log(data);
				if(data.result == 'OK') {
					$('textarea', self).val('');
					$('.chat-history').prepend(data.newMessBlock);
					$('.chat-history .mess-item').eq(0).slideDown(400);
				}
				canSend = true;
			}	
		});
		return false;
	});
});